#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   app.py
@Time    :   2020/09/29 14:44:25
@Author  :   fengzhilaoling 
@Version :   1.0
@Contact :   fengzhilaoling@163.com
'''
from flask import Flask
from flask import request
from flask import render_template
from flask import make_response
from flask import redirect
from flask import url_for
from flask import flash
from flask import send_from_directory
from werkzeug.utils import secure_filename  # 使用这个是为了确保filename是安全的
from os import path
from os import makedirs
from os import urandom


img_type = ['png', 'jpg', 'tif']  # 设置图片类型
app = Flask(__name__)
app.config['SECRET_KEY'] = urandom(24)  # flash是指session是用到


@app.route('/upload/', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST':
        img = request.files['image']  # 获取file对象
        base_dir = path.abspath(path.dirname(__file__))  # 获取当前文件的绝对路径
        upload_path = path.join(base_dir, 'static/upload/')  # 拼接文件保存路径
        # 使用lambda函数判断 文件保存路径是否存在，不存在创建
        def make_path(upload_path): return makedirs(
            upload_path) if not path.isdir(upload_path) else True
        make_path(upload_path)
        file_name = secure_filename(img.filename)  # 获取文件名
        image_type = file_name.split('.')[-1]  # 获取文件的类型
        # 判断是否为指定的 扩展名的文件
        if image_type in img_type:
            file_name = upload_path + file_name  # 拼接处文件的具体的保存路径
            print(file_name)
            img.save(file_name)  # 将文件写入
            show_image = open(file_name, 'rb').read()  # 读取文件
            response = make_response(show_image)  # 将文件转为，response方式进行返回
            response.headers['Content-Type'] = f'image/{image_type}'
            return response
        else:
            flash('Unknown Types!', 'danger')  # 文件不存在，提示
    return render_template('upload.html')


@app.route('/download/')
def download():
    base_dir = path.abspath(path.dirname(__file__))
    down_dir = path.join(base_dir, 'static/upload/')
    # filename = '4b6c230e840facdfea13ba35c446813.jpg'
    filename = '文件.txt'
    return send_from_directory(down_dir, filename=filename, as_attachment=True)


if __name__ == "__main__":
    app.run(debug=True)
